package org.sam.beatles.widget;

import static com.metsci.glimpse.docking.DockingUtils.requireIcon;
import static com.metsci.glimpse.docking.ViewCloseOption.VIEW_AUTO_CLOSEABLE;

import javax.swing.JComponent;

import org.apache.commons.lang3.StringUtils;
import org.sam.beatles.MainFrameContainer;
import org.sam.beatles.event.OpenDockWindowEvent;
import org.sam.beatles.ui.UIBuilder;
import org.sam.beatles.utils.BeanUtil;
import org.sam.swing.JSPanel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;

import com.metsci.glimpse.docking.Tile;
import com.metsci.glimpse.docking.View;

/**
 * GlimpseDock 实现的多文档窗口
 * 接受dock window打开事件的操作
 * 
 * @author sam
 *
 */
@Controller
public class GlimpseDockingEventWidget {

	/**
	 * 主窗口
	 */
	@Autowired
	private MainFrameContainer view;

	/**
	 * bean操作助手工具
	 */
	@Autowired
	private BeanUtil beanUtil;

	/**
	 * 接收
	 * 
	 * @param event
	 */
	@EventListener(OpenDockWindowEvent.class)
	@Async
	public void openDockWindowEventHandler(OpenDockWindowEvent event) {
		if (event == null || event.getClz() == null || StringUtils.isEmpty(event.getTitle()))
			return;

		if (this.view == null)
			return;

		if (!this.view.getViewParts().containsKey(MainFrameContainer.TILE_MAIN))
			return;

		JComponent jComponent = this.view.getViewParts().get(MainFrameContainer.TILE_MAIN);
		if (jComponent == null || !(jComponent instanceof Tile))
			return;

		Tile tile = (Tile) jComponent;

		try {
			int iCount = tile.numViews();
			for (int i = 0; i < iCount; i++) {
				View v = tile.view(i);
				if (v.viewId.equals(event.getClz().getSimpleName())) {
					tile.selectView(v);
					return;
				}
			}

			// 重新生成窗口
			JSPanel newInstance = event.getClz().getDeclaredConstructor().newInstance();
			beanUtil.scanForAutoWired(newInstance);
			// 注入完成后再生成控件
			if (newInstance instanceof UIBuilder) {
				((UIBuilder) newInstance).buildCompents();
			}

			View v = new View(event.getClz().getSimpleName(), newInstance, event.getTitle(), VIEW_AUTO_CLOSEABLE, null,
					requireIcon("jframe.png"), null);
			tile.addView(v, iCount);
			tile.selectView(v);

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
